package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tangyh.basic.context.ContextUtil;
import top.tangyh.basic.exception.BizException;
import top.tangyh.basic.utils.DateUtils;
import top.tangyh.lamp.care.entity.BGenItem;
import top.tangyh.lamp.care.mapper.BIoRecordMapper;
import top.tangyh.lamp.care.service.BGenItemService;
import top.tangyh.lamp.care.service.BIoRecordService;
import top.tangyh.basic.base.service.impl.SuperServiceImpl;
import top.tangyh.lamp.care.manager.BIoRecordManager;
import top.tangyh.lamp.care.entity.BIoRecord;
import top.tangyh.lamp.care.service.BWorkPlanService;
import top.tangyh.lamp.care.vo.query.*;
import top.tangyh.lamp.care.vo.result.*;
import top.tangyh.lamp.care.vo.save.BIoRecordSaveVO;
import top.tangyh.lamp.care.vo.save.IoRecordInVO;
import top.tangyh.lamp.care.vo.save.IoSuspensionFrameDataInVo;
import top.tangyh.lamp.care.vo.update.BIoRecordUpdateVO;
import top.tangyh.lamp.common.utils.PDateUtils;
import top.tangyh.lamp.common.utils.YDateUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static top.tangyh.lamp.common.constant.CommonConstant.YES_NUMBER;

/**
 * <p>
 * 业务实现类
 * 出入量记录表
 * </p>
 *
 * @author zqb
 * @date 2024-07-23 10:12:06
 * @create [2024-07-23 10:12:06] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class BIoRecordServiceImpl extends SuperServiceImpl<BIoRecordManager, Long, BIoRecord> implements BIoRecordService {

    private final BIoRecordMapper bIoRecordMapper;

    private final BWorkPlanService bWorkPlanService;


    private final BGenItemService bGenItemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addOrUpdateYxIoRecord(IoRecordInVO ioRecordInVO) {

        BIoRecord bIoRecord = new BIoRecord();
        BeanUtils.copyProperties(ioRecordInVO, bIoRecord);
        try {
//            check(BIoRecord);
            if (null == bIoRecord.getId()) {
                bIoRecord.setCreatedBy(ContextUtil.getUserId());
                bIoRecord.setUpdatedBy(ContextUtil.getUserId());
                bIoRecord.setIsYaoSum(1);
                bIoRecord.setTime(PDateUtils.getDateTimeOfTimestamp(ioRecordInVO.getTimeLong()));

                ZoneId zone = ZoneId.systemDefault();
                LocalDateTime realTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(ioRecordInVO.getTimeLong()), zone);
                bIoRecord.setRealTime(realTime);
                bIoRecord.setDyAmount(ioRecordInVO.getIoValue());
                bIoRecord.setDyAmountUnit("ml");
                bIoRecordMapper.insert(bIoRecord);
                return bIoRecord.getId();
//                return ApiR.success(BIoRecord.getId());
            } else {
                //是否本人修改 判断
//                if (null != SecurityUtil.checkRecordAuth(BIoRecord.getCreateBy(), BIoRecord.getUpdateBy())) {
//                    throw new BizException(SecurityUtil.checkRecordAuth(BIoRecord.getCreateBy(), BIoRecord.getUpdateBy()));
//                }

                LambdaUpdateWrapper<BIoRecord> userUpdateWrapper = new LambdaUpdateWrapper<>();

                userUpdateWrapper.set(BIoRecord::getIoValue, ioRecordInVO.getIoValue());
                userUpdateWrapper.set(BIoRecord::getRealTime, new Date(ioRecordInVO.getRealTimeLong()));
                userUpdateWrapper.set(BIoRecord::getMedication, ioRecordInVO.getMedication());

                userUpdateWrapper.eq(BIoRecord::getId, ioRecordInVO.getId());
                bIoRecordMapper.update(null, userUpdateWrapper);


                return bIoRecord.getId();

            }
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            return (long) -1;
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map addOrUpdateYxIoRecordBatch(List<IoRecordInVO> ioRecordPOs) {
        Map map = new HashMap();
        List<Long> ids = new ArrayList<>();
        List<Boolean> booleans = new ArrayList<>();
        for (int i = 0; i < ioRecordPOs.size(); i++) {
            IoRecordInVO ioRecordInVO = ioRecordPOs.get(i);
            BIoRecord ioRecordPO = new BIoRecord();
            BeanUtils.copyProperties(ioRecordInVO, ioRecordPO);

            try {
                if (null == ioRecordPO.getId()) {
                    ioRecordPO.setCreatedBy(ContextUtil.getUserId());
                    ioRecordPO.setUpdatedBy(ContextUtil.getUserId());
                    ioRecordPO.setIsYaoSum(1);
                    ioRecordPO.setTime(PDateUtils.getDateTimeOfTimestamp(ioRecordInVO.getTimeLong()));
//                    ioRecordPO.setSource("hand");
                    ZoneId zone = ZoneId.systemDefault();
                    LocalDateTime realTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(ioRecordInVO.getRealTimeLong()), zone);
                    ioRecordPO.setRealTime(realTime);
                    ioRecordPO.setDyAmount(ioRecordInVO.getIoValue());
                    ioRecordPO.setDyAmountUnit("ml");
                    bIoRecordMapper.insert(ioRecordPO);
                    ids.add(ioRecordPO.getId());

                } else {
                    //判断是否本人修改
//                    if (null != SecurityUtil.checkRecordAuth(ioRecordPO.getCreateBy(), ioRecordPO.getUpdateBy())) {
//                        throw new BadRequestException(SecurityUtil.checkRecordAuth(ioRecordPO.getCreateBy(), ioRecordPO.getUpdateBy()));
//                    }

                    if (ioRecordInVO.getModelCode().equals("crl-out")) {

                        if (StringUtil.isEmpty(ioRecordInVO.getIoValue())) {
                            bIoRecordMapper.deleteById(ioRecordInVO.getId());
                        } else {
                            LambdaUpdateWrapper<BIoRecord> userUpdateWrapper = new LambdaUpdateWrapper<>();
                            userUpdateWrapper.set(BIoRecord::getIoValue, ioRecordPO.getIoValue());
                            userUpdateWrapper.set(BIoRecord::getRealTime, new Date(ioRecordInVO.getRealTimeLong()));
                            userUpdateWrapper.set(BIoRecord::getMedication, ioRecordInVO.getMedication());
                            userUpdateWrapper.set(BIoRecord::getDyAmount, ioRecordInVO.getIoValue());
                            userUpdateWrapper.eq(BIoRecord::getId, ioRecordInVO.getId());
                            bIoRecordMapper.update(null, userUpdateWrapper);
                        }
                    } else if (ioRecordInVO.getModelCode().equals("crl-in")) {
                        LambdaUpdateWrapper<BIoRecord> userUpdateWrapper = new LambdaUpdateWrapper<>();

                        userUpdateWrapper.set(BIoRecord::getIoValue, ioRecordPO.getIoValue());
                        userUpdateWrapper.set(BIoRecord::getRealTime, new Date(ioRecordInVO.getRealTimeLong()));
                        userUpdateWrapper.set(BIoRecord::getMedication, ioRecordInVO.getMedication());
                        userUpdateWrapper.set(BIoRecord::getDyAmount, ioRecordInVO.getIoValue());
                        userUpdateWrapper.eq(BIoRecord::getId, ioRecordInVO.getId());
                        bIoRecordMapper.update(null, userUpdateWrapper);
                    }


                }
            } catch (DuplicateKeyException e) {
                e.printStackTrace();

            }
        }
        map.put("add", ids);
        map.put("update", booleans);
        return map;
    }

    @Override
    public Map<String, Map<String, List<IoRecordVO>>> listOfIoRecord(SelectStatisticParam statisticParam) {

        WorkPlanDetailQueryVO queryVO = new WorkPlanDetailQueryVO();
        queryVO.setModuleId("crl");
        queryVO.setCurrentDate(DateUtils.parse(statisticParam.getHoverTime(), "yyyy-MM-dd").getTime());
        List<WorkPlanDetailOutVO> workPlanDetailOutVOList = bWorkPlanService.selectDetailListByQuery(queryVO);
        if (CollectionUtil.isNotEmpty(workPlanDetailOutVOList)) {
            statisticParam.setStartTime(workPlanDetailOutVOList.get(0).getStartTime());
        }
        if (CollectionUtil.isNotEmpty(workPlanDetailOutVOList)) {
            statisticParam.setEndTime(workPlanDetailOutVOList.get(workPlanDetailOutVOList.size() - 1).getEndTime());
        }

        List<IoRecordVO> list = bIoRecordMapper.selectListOfRecordIo(statisticParam);
        List<IoRecordVO> listNull = list.stream().filter(e -> null == e.getId()).collect(Collectors.toList());
        List<IoRecordVO> listOut = list.stream().filter(e -> e.getModelCode().equals("crl-out")).collect(Collectors.toList());
        List<IoRecordVO> listIsMasterFalse = list.stream().filter(e -> null != e.getIsMaster() && e.getIsMaster() == 0).collect(Collectors.toList());


        List<IoRecordVO> listMaster = list.stream().filter(e -> null != e.getIsMaster() && e.getIsMaster() == 1).collect(Collectors.toList());

        List<IoRecordVO> listMasterEnd = new ArrayList<>();
        for (int i = 0; i < listMaster.size(); i++) {
            IoRecordVO yxIoRecordVOMaster = listMaster.get(i);
            //主药下的副药
            List<BIoRecord> poListSun = bIoRecordMapper.selectIoRecordByGroupId(yxIoRecordVOMaster.getHospitalNumber(), yxIoRecordVOMaster.getPatientIdent(), yxIoRecordVOMaster.getGroupId(), yxIoRecordVOMaster.getPlanTime());
            poListSun = poListSun.stream().filter(e -> e.getDyAmountUnit().equals("ml")).collect(Collectors.toList());

            BigDecimal totalAmount = new BigDecimal(yxIoRecordVOMaster.getIoValue());
            for (int j = 0; j < poListSun.size(); j++) {
                totalAmount = totalAmount.add(new BigDecimal(poListSun.get(j).getIoValue()));
            }
            yxIoRecordVOMaster.setIoValue(totalAmount.toString());
            listMasterEnd.add(yxIoRecordVOMaster);
        }

        listMasterEnd.addAll(listNull);
        listMasterEnd.addAll(listOut);
        listMasterEnd.addAll(listIsMasterFalse);


        Map<String, List<IoRecordVO>> collects = listMasterEnd.stream().collect(Collectors.groupingBy(IoRecordVO::getModelCode));

        Map<String, Map<String, List<IoRecordVO>>> collects_result = new HashMap<>();
        for (Map.Entry<String, List<IoRecordVO>> entry : collects.entrySet()) {
            Map<String, List<IoRecordVO>> collects_code = entry.getValue().stream().collect(Collectors.groupingBy(IoRecordVO::getItemCode));

            collects_result.put(entry.getKey(), collects_code);

        }

        return collects_result;
    }

    @Override
    public List<IoItemVO> itemQuery(IoItemQueryParam ioItemQueryParam) {
        List<BGenItem> pat = bGenItemService.queryItemByPidAndCode(ioItemQueryParam.getModelCode(), null, ioItemQueryParam.getPatientIdent());
        List<BGenItem> sys = bGenItemService.queryItemByPidAndCode(ioItemQueryParam.getModelCode(), null, null);
        Map<String, BGenItem> patmap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(pat)) {
            patmap = pat.stream().collect(Collectors.toMap(BGenItem::getItemCode, Function.identity()));
        }
        List<BGenItem> parents = new ArrayList<>();
        for (BGenItem item : sys) {
            BGenItem patitem = patmap.get(item.getItemCode());
            if (null == patitem) {
                if (null != item.getIsVisible() && item.getIsVisible() == 1) {
                    parents.add(item);
                }
            } else {
                if (null != patitem.getIsVisible() && patitem.getIsVisible() == 1) {
                    parents.add(patitem);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(parents)) {
            return BeanUtil.copyToList(parents, IoItemVO.class);
        }
        return new ArrayList<>();
    }


    @Override
    public SumOfIoStatisticslVO selectSumStatistic(String hospitalNumber, String startTime, String endTime) {
        SumOfIoStatisticslVO sumOfIoStatisticslVO = new SumOfIoStatisticslVO();

        List<IoDetailVO> listDetail = new ArrayList<>();
        List<IoModelVO> listModel = new ArrayList<>();

        List<BIoRecord> listIn = bIoRecordMapper.selectIoRecordOfList(hospitalNumber, "crl-in", startTime, endTime);
        List<BIoRecord> listMasterOut = bIoRecordMapper.selectIoRecordOfList(hospitalNumber, "crl-out", startTime, endTime);

        List<BIoRecord> listHisMaster = listIn.stream().filter(e -> e.getIsMaster() == 1 && e.getSource().equals("his")).collect(Collectors.toList());
        List<BIoRecord> listNoHis = listIn.stream().filter(e -> e.getSource().equals("hand") || e.getSource().equals("care")).collect(Collectors.toList());

        //入量明细汇总
        List<BIoRecord> listMasterEnd = new ArrayList<>();
        for (int i = 0; i < listHisMaster.size(); i++) {
            BIoRecord yxIoRecordPOMaste = listHisMaster.get(i);
            List<BIoRecord> poListSun = bIoRecordMapper.selectIoRecordByGroupId(yxIoRecordPOMaste.getHospitalNumber(), yxIoRecordPOMaste.getPatientIdent(), yxIoRecordPOMaste.getGroupId(), yxIoRecordPOMaste.getPlanTime());
            poListSun = poListSun.stream().filter(e -> e.getDyAmountUnit().equals("ml")).collect(Collectors.toList());
            BigDecimal totalAmount = new BigDecimal(yxIoRecordPOMaste.getIoValue());
            for (int j = 0; j < poListSun.size(); j++) {
                totalAmount = totalAmount.add(new BigDecimal(poListSun.get(j).getIoValue()));
            }
            yxIoRecordPOMaste.setIoValue(totalAmount.toString());
            listMasterEnd.add(yxIoRecordPOMaste);
        }

        listMasterEnd.addAll(listNoHis);


        //出量明细汇总
        List<BIoRecord> listMasterEndOut = new ArrayList<>();
        for (int i = 0; i < listMasterOut.size(); i++) {
            BIoRecord yxIoRecordPOMaste = listMasterOut.get(i);
            List<BIoRecord> poListSun = bIoRecordMapper.selectIoRecordByGroupId(yxIoRecordPOMaste.getHospitalNumber(), yxIoRecordPOMaste.getPatientIdent(), yxIoRecordPOMaste.getGroupId(), yxIoRecordPOMaste.getPlanTime());
            poListSun = poListSun.stream().filter(e -> e.getDyAmountUnit().equals("ml")).collect(Collectors.toList());
            BigDecimal totalAmount = new BigDecimal(yxIoRecordPOMaste.getIoValue());
            for (int j = 0; j < poListSun.size(); j++) {
                totalAmount = totalAmount.add(new BigDecimal(poListSun.get(j).getIoValue()));
            }
            yxIoRecordPOMaste.setIoValue(totalAmount.toString());
            listMasterEndOut.add(yxIoRecordPOMaste);
        }


        listMasterEnd = listMasterEnd.stream().filter(e -> null != e.getItemName()).collect(Collectors.toList());

        Map<String, DoubleSummaryStatistics> result = listMasterEnd.stream()
                .collect(Collectors.groupingBy(
                        m -> m.getItemName(),
                        Collectors.summarizingDouble(
                                m -> Double.parseDouble(m.getIoValue()))));


        listMasterEndOut = listMasterEndOut.stream().filter(e -> null != e.getItemName()).collect(Collectors.toList());

        Map<String, DoubleSummaryStatistics> resultOut = listMasterEndOut.stream()
                .collect(Collectors.groupingBy(
                        m -> m.getItemName(),
                        Collectors.summarizingDouble(
                                m -> Double.parseDouble(m.getIoValue()))));

        Iterator<Map.Entry<String, DoubleSummaryStatistics>> entries = result.entrySet().iterator();
        Iterator<Map.Entry<String, DoubleSummaryStatistics>> entriesOut = resultOut.entrySet().iterator();

        BigDecimal inSum = new BigDecimal(0);
        BigDecimal outSum = new BigDecimal(0);

        while (entries.hasNext()) {

            Map.Entry<String, DoubleSummaryStatistics> entry = entries.next();

            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            IoDetailVO ioDetailVO = new IoDetailVO();
            ioDetailVO.setSumValue(new BigDecimal(entry.getValue().getSum()));
            ioDetailVO.setItemName(entry.getKey());
            ioDetailVO.setModelCode("crl-in");
            listDetail.add(ioDetailVO);
            inSum = inSum.add(new BigDecimal(entry.getValue().getSum()));
        }


        while (entriesOut.hasNext()) {

            Map.Entry<String, DoubleSummaryStatistics> entryOut = entriesOut.next();

            System.out.println("Key = " + entryOut.getKey() + ", Value = " + entryOut.getValue());
            IoDetailVO ioDetailVO = new IoDetailVO();
            ioDetailVO.setSumValue(new BigDecimal(entryOut.getValue().getSum()));
            ioDetailVO.setItemName(entryOut.getKey());
            ioDetailVO.setModelCode("crl-out");
            listDetail.add(ioDetailVO);
            outSum = outSum.add(new BigDecimal(entryOut.getValue().getSum()));
        }


        IoModelVO ioModelVOIn = new IoModelVO();
        ioModelVOIn.setModelCode("crl-in");
        ioModelVOIn.setSumValue(inSum);

        IoModelVO ioModelVOOut = new IoModelVO();
        ioModelVOOut.setModelCode("crl-out");
        ioModelVOOut.setSumValue(outSum);

        listModel.add(ioModelVOIn);
        listModel.add(ioModelVOOut);

        sumOfIoStatisticslVO.setDetailVOList(listDetail);
        sumOfIoStatisticslVO.setModelVOList(listModel);
        return sumOfIoStatisticslVO;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByTime(String time) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("time", time);
//        List<BIoRecord> ioRecordPOs = bIoRecordMapper.selectList(wrapper);
        //非本人 删除判断
//        if (CollectionUtil.isNotEmpty(ioRecordPOs)) {
//            if (null != SecurityUtil.checkRecordAuth(ioRecordPOs.get(0).getCreateBy(), ioRecordPOs.get(0).getUpdateBy())) {
//                throw new BadRequestException(SecurityUtil.checkRecordAuth(ioRecordPOs.get(0).getCreateBy(), ioRecordPOs.get(0).getUpdateBy()));
//            }
//        }

        int rows = bIoRecordMapper.delete(wrapper);
        return rows;
    }


    @Override
    public List<IoSuspensionFrameData> selectIoSuspensionFrameData(IoSuspensionFrameDataInVo queryVO) {

        List<IoSuspensionFrameData> listIoSuspensionFrameDataResult = new ArrayList<>();

        LambdaQueryWrapper<BIoRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BIoRecord::getHospitalNumber, queryVO.getHospitalNumber());
        queryWrapper.eq(BIoRecord::getItemCode, queryVO.getItemCode());
        queryWrapper.ge(queryVO.getStartTime() != null, BIoRecord::getRealTime, new Date(queryVO.getStartTime()));
        queryWrapper.le(queryVO.getEndTime() != null, BIoRecord::getRealTime, new Date(queryVO.getEndTime()));
        List<BIoRecord> list = bIoRecordMapper.selectList(queryWrapper);

        List<BIoRecord> listHisOrBulu = list.stream().filter(e -> e.getSource().equals("his") || e.getSource().equals("bulu")).collect(Collectors.toList());

        List<BIoRecord> listHand = list.stream().filter(e -> e.getSource().equals("hand") || e.getSource().equals("care")).collect(Collectors.toList());


        //根据getGroupId和getPlanTime字段进行分组
        Map<String, List<BIoRecord>> mapHis = listHisOrBulu.stream().collect(
                Collectors.groupingBy(
                        score -> score.getGroupId() + "#" + score.getPlanTime()
                ));

        for (Map.Entry<String, List<BIoRecord>> entry : mapHis.entrySet()) {

            List<BIoRecord> poList = entry.getValue();


            //拿到主药
            Optional<BIoRecord> havePoListMaster = poList.stream().filter(e -> e.getIsMaster() == 1).findFirst();
            BIoRecord yxIoRecordPOMaste = new BIoRecord();
            if (havePoListMaster.isPresent()) {
                yxIoRecordPOMaste = havePoListMaster.get();
            }

            List<BIoRecord> poListSun = bIoRecordMapper.selectIoRecordByGroupId(yxIoRecordPOMaste.getHospitalNumber(), yxIoRecordPOMaste.getPatientIdent(), yxIoRecordPOMaste.getGroupId(), yxIoRecordPOMaste.getPlanTime());


            StringBuilder name = new StringBuilder();
            name.append(yxIoRecordPOMaste.getMedication() + " " + yxIoRecordPOMaste.getDyAmount() + " " + yxIoRecordPOMaste.getDyAmountUnit());


            for (int i = 0; i < poListSun.size(); i++) {
                BIoRecord yxIoRecordPOSun = poListSun.get(i);
                if (havePoListMaster.isPresent()) {
                    name.append("+" + yxIoRecordPOSun.getMedication() + " " + yxIoRecordPOSun.getDyAmount() + " " + yxIoRecordPOSun.getDyAmountUnit());
                } else {
                    name.append(yxIoRecordPOSun.getMedication() + " " + yxIoRecordPOSun.getDyAmount() + " " + yxIoRecordPOSun.getDyAmountUnit());
                }
            }

            IoSuspensionFrameData ioSuspensionFrameData = new IoSuspensionFrameData();
            ioSuspensionFrameData.setMedicationName(name.toString());
            ioSuspensionFrameData.setExeTime(Timestamp.valueOf(yxIoRecordPOMaste.getRealTime()).getTime());
            listIoSuspensionFrameDataResult.add(ioSuspensionFrameData);
        }

        for (int i = 0; i < listHand.size(); i++) {
            BIoRecord yxIoRecordPO = listHand.get(i);
            IoSuspensionFrameData ioSuspensionFrameData = new IoSuspensionFrameData();
            ioSuspensionFrameData.setMedicationName(yxIoRecordPO.getMedication() + " " + yxIoRecordPO.getDyAmount() + " " + yxIoRecordPO.getDyAmountUnit());
            ioSuspensionFrameData.setExeTime(Timestamp.valueOf(yxIoRecordPO.getRealTime()).getTime());
            listIoSuspensionFrameDataResult.add(ioSuspensionFrameData);
        }


        return listIoSuspensionFrameDataResult;
    }


    @Override
    public List<DataForIoOUtVO> selectDialogList(DataForIoVOQuery queryVO) {

        //来自his
        LambdaQueryWrapper<BIoRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BIoRecord::getItemCode, queryVO.getItemCode());
        queryWrapper.eq(BIoRecord::getHospitalNumber, queryVO.getHospitalNumber())
                .eq(BIoRecord::getIsMaster, YES_NUMBER)
                .eq(BIoRecord::getSource, "his")
                .ge(BIoRecord::getRealTime, new Date(queryVO.getStartTime()))
                .le(BIoRecord::getRealTime, new Date(queryVO.getEndTime()));


        List<DataForIoOUtVO> listResult = new ArrayList<>();
        List<BIoRecord> listMaster = bIoRecordMapper.selectList(queryWrapper);

        List<BIoRecord> listMasterSun = new ArrayList<>();

        for (int i = 0; i < listMaster.size(); i++) {
            BIoRecord yxIoRecordPOMaster = listMaster.get(i);
            List<BIoRecord> poListSun = bIoRecordMapper.selectIoRecordByGroupId(yxIoRecordPOMaster.getHospitalNumber(), yxIoRecordPOMaster.getPatientIdent(), yxIoRecordPOMaster.getGroupId(), yxIoRecordPOMaster.getPlanTime());

            poListSun.forEach(item -> item.setRealTime(yxIoRecordPOMaster.getRealTime()));


            listMasterSun.add(yxIoRecordPOMaster);
            listMasterSun.addAll(poListSun);
        }


        for (int i = 0; i < listMasterSun.size(); i++) {
            BIoRecord yxIoRecordPO = listMasterSun.get(i);
            DataForIoOUtVO yaoForIoOUtVO = new DataForIoOUtVO();
            yaoForIoOUtVO.setExeTime(Timestamp.valueOf(yxIoRecordPO.getRealTime()).getTime());
            yaoForIoOUtVO.setYtCount(new BigDecimal(yxIoRecordPO.getIoValue()));
            if (yxIoRecordPO.getSource().equals("bulu")) {
                yaoForIoOUtVO.setIsDiy(2);
            } else if (yxIoRecordPO.getSource().equals("his")) {
                yaoForIoOUtVO.setIsDiy(0);
            }
            yaoForIoOUtVO.setMedicationName(yxIoRecordPO.getMedication());
            if (yxIoRecordPO.getSource().equals("his") || yxIoRecordPO.getSource().equals("bulu")) {
                yaoForIoOUtVO.setIsFromio(0);
            } else if (yxIoRecordPO.getSource().equals("hand") || yxIoRecordPO.getSource().equals("care")) {
                yaoForIoOUtVO.setIsFromio(1);
            }
            if (yxIoRecordPO.getSource().equals("his")) {
                yaoForIoOUtVO.setIsDiy(1);
            } else if (yxIoRecordPO.getSource().equals("bulu")) {
                yaoForIoOUtVO.setIsDiy(2);
            } else if (yxIoRecordPO.getSource().equals("hand") || yxIoRecordPO.getSource().equals("care")) {
                yaoForIoOUtVO.setIsDiy(0);
            }
            yaoForIoOUtVO.setIsMaster(yxIoRecordPO.getIsMaster());

            yaoForIoOUtVO.setCreatedBy(yxIoRecordPO.getCreatedBy());
            yaoForIoOUtVO.setUpdatedBy(yxIoRecordPO.getUpdatedBy());
            yaoForIoOUtVO.setCreatedTime(yxIoRecordPO.getCreatedTime());
            yaoForIoOUtVO.setUpdatedTime(yxIoRecordPO.getUpdatedTime());
            yaoForIoOUtVO.setId(yxIoRecordPO.getId());

            listResult.add(yaoForIoOUtVO);
        }

        //来自手动
        List<String> listSource = new ArrayList<>();
        listSource.add("hand");
        listSource.add("care");
        listSource.add("bulu");

        LambdaQueryWrapper<BIoRecord> queryWrapperHand = new LambdaQueryWrapper<>();
        queryWrapperHand.eq(BIoRecord::getItemCode, queryVO.getItemCode());
        queryWrapperHand.eq(BIoRecord::getHospitalNumber, queryVO.getHospitalNumber())
                .in(BIoRecord::getSource, listSource)
                .ge(BIoRecord::getRealTime, new Date(queryVO.getStartTime()))
                .le(BIoRecord::getRealTime, new Date(queryVO.getEndTime()));


        List<BIoRecord> listHand = bIoRecordMapper.selectList(queryWrapperHand);

        for (int i = 0; i < listHand.size(); i++) {
            BIoRecord yxIoRecordPO = listHand.get(i);
            DataForIoOUtVO yaoForIoOUtVO = new DataForIoOUtVO();
            yaoForIoOUtVO.setExeTime(Timestamp.valueOf(yxIoRecordPO.getRealTime()).getTime());
            yaoForIoOUtVO.setYtCount(new BigDecimal(yxIoRecordPO.getIoValue()));
            if (yxIoRecordPO.getSource().equals("bulu")) {
                yaoForIoOUtVO.setIsDiy(2);
            } else if (yxIoRecordPO.getSource().equals("his")) {
                yaoForIoOUtVO.setIsDiy(0);
            }
            yaoForIoOUtVO.setMedicationName(yxIoRecordPO.getMedication());
            if (yxIoRecordPO.getSource().equals("his") || yxIoRecordPO.getSource().equals("bulu")) {
                yaoForIoOUtVO.setIsFromio(0);
            } else if (yxIoRecordPO.getSource().equals("hand") || yxIoRecordPO.getSource().equals("care")) {
                yaoForIoOUtVO.setIsFromio(1);
            }
            if (yxIoRecordPO.getSource().equals("his")) {
                yaoForIoOUtVO.setIsDiy(1);
            } else if (yxIoRecordPO.getSource().equals("bulu")) {
                yaoForIoOUtVO.setIsDiy(2);
            } else if (yxIoRecordPO.getSource().equals("hand") || yxIoRecordPO.getSource().equals("care")) {
                yaoForIoOUtVO.setIsDiy(0);
            }
            yaoForIoOUtVO.setIsMaster(yxIoRecordPO.getIsMaster());
            yaoForIoOUtVO.setCreatedBy(yxIoRecordPO.getCreatedBy());
            yaoForIoOUtVO.setUpdatedBy(yxIoRecordPO.getUpdatedBy());
            yaoForIoOUtVO.setCreatedTime(yxIoRecordPO.getCreatedTime());
            yaoForIoOUtVO.setUpdatedTime(yxIoRecordPO.getUpdatedTime());
            yaoForIoOUtVO.setId(yxIoRecordPO.getId());

            listResult.add(yaoForIoOUtVO);
        }

        return listResult.stream().sorted(Comparator.comparing(DataForIoOUtVO::getExeTime)).collect(Collectors.toList());
    }


    @Override
    public List<TemperateIODataVO> selectSumOfNlList(String hospitalNumber, String itemCode, String startTime, String endTime) {
        return bIoRecordMapper.selectSumOfNlList(hospitalNumber, itemCode, startTime, endTime);
    }

    @Override
    public List<TemperateIODataVO> selectSumOfLiuLiangList(String hospitalNumber, String startTime, String endTime) {
        List<TemperateIODataVO> list = bIoRecordMapper.selectSumOfLiuLiangList(hospitalNumber, startTime, endTime);
        list.forEach(object -> object.setSumValue(YDateUtils.trimNoZeros(object.getSumValue())));
        return list;
    }

    @Override
    public List<TemperateIODataVO> selectSumOfOutInList(String hospitalNumber, String startTime, String endTime) {
        List<TemperateIODataVO> list = bIoRecordMapper.selectSumOfOutInList(hospitalNumber, startTime, endTime);
        //去除 .0
        list.forEach(object -> object.setSumValue(YDateUtils.trimNoZeros(object.getSumValue())));

        return list;
    }


    @Override
    public void saveList(List<IoRecordInVO> io, Long time, String operator, String account, String patientIdent, String hospitalNumber) {
        bIoRecordMapper.deleteInOld(time, operator, account, patientIdent, hospitalNumber);
        Date ftime = YDateUtils.strToDate(YDateUtils.format(YDateUtils.addDateSeconds(YDateUtils.addDateHours(new Date(time), 1), -1), "yyyy-MM-dd HH") + ":00:00", YDateUtils.DATE_TIME_PATTERN);
        bIoRecordMapper.deleteOutOld(ftime, operator, account, patientIdent, hospitalNumber);
        if (CollectionUtil.isEmpty(io)) {
            return;
        }
        List<BIoRecord> add = new ArrayList<>();
        for (int i = 0; i < io.size(); i++) {
            IoRecordInVO yxIoRecordInVO = io.get(i);
            BIoRecord yxIoRecordPO = new BIoRecord();
            BeanUtils.copyProperties(yxIoRecordInVO, yxIoRecordPO);

            yxIoRecordPO.setCreatedBy(Long.valueOf(operator));
            yxIoRecordPO.setUpdatedBy(Long.valueOf(operator));
            yxIoRecordPO.setIsYaoSum(1);
            yxIoRecordPO.setTime(YDateUtils.timestamToDatetime(ftime.getTime()));
            ZoneId zone = ZoneId.systemDefault();
            LocalDateTime realTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), zone);
            yxIoRecordPO.setRealTime(realTime);
            yxIoRecordPO.setDyAmount(yxIoRecordInVO.getIoValue());
            yxIoRecordPO.setDyAmountUnit("ml");
            yxIoRecordPO.setSource("care");
            add.add(yxIoRecordPO);
        }
        saveBatch(add);
    }
}


